<template>
  <page-layout>
    <a-row :gutter="10">
      <a-col :md="leftColMd" :sm="24">
        <a-card :bordered="false">
          <!-- 查询区域 -->
          <div >
            <a-form @keyup.enter.native="searchQueryRole">
              <a-row :gutter="12">
                <a-col :md="12" :sm="12">
                  <a-form-item label="角色名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input placeholder="输入角色名称" v-model="queryParamRole.name"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :md="12" :sm="12">
                  <a-form-item>
                    <a-button type="primary" @click="searchQueryRole()" icon="search">查询</a-button>
                    <a-button type="primary" @click="searchResetRole()" icon="reload" style="margin-left: 8px">重置</a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- table区域-begin -->
          <div>
            <vxe-grid
              id="RoleList"
              keep-source
              ref="vxeTableRole"
              :height="null"
              v-bind="optionsRole"
              :columns="columnsRole"
              :data="dataSourceRole"
              :radio-config="{trigger:'cell'}"
              @radio-change="onSelectChangeRole"
            >
            <template v-slot:toolbar_buttons>
              <div class="table-operator">
                <a-button @click="handleAddRole" icon="plus" class="theme--perfect-button">添加</a-button>
              </div>
            </template>
            <template #action="{ row }">
              <template>
                <a @click="handleEditRole(row)" >编辑</a>
                <a-divider type="vertical" />
                <a-dropdown>
                  <a class="ant-dropdown-link">
                    更多 <a-icon type="down"/>
                  </a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a href="javascript:;" @click="handleEditPerssion(row)">菜单权限</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteRole(row.id)">
                        <a>删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </template>
            </template>
            <template v-slot:pager>
              <vxe-pager
                :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
                :current-page.sync="ipaginationRole.currentPage"
                :page-size.sync="ipaginationRole.pageSize"
                :total="ipaginationRole.total"
                @page-change="handlePageChange"
              >
              </vxe-pager>
            </template>
          </vxe-grid>
          </div>
        </a-card>
      </a-col>
      <a-col :md="rightColMd" :sm="24">
        <a-card :bordered="false">
          <div class="table-page-search-wrapper">
            <a-form @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :md="8" >
                  <a-form-item label="账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input style="width:100%;" placeholder="输入账号模糊查询" v-model="queryParam.username"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :md="8">
                  <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input placeholder="输入姓名模糊查询" v-model="queryParam.realname"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :md="8">
                  <a-form-item>
                    <a-button type="primary" @click="searchQuery()" icon="search">查询</a-button>
                    <a-button type="primary" @click="searchReset()" icon="reload" style="margin-left: 8px">重置</a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <!-- table区域-begin -->
          <div>
            <vxe-grid
              id="UserList"
              ref="vxeTable"
              :height="null"
              v-bind="options"
              rowId="actorId"
              @checkbox-change="onSelectChange"
              @checkbox-all="onSelectChange"
              @page-change="handlePageChange"
            >
            <template v-slot:toolbar_buttons>
              <div class="table-operator">
                <a-button @click="handleAdd" icon="plus" class="theme--perfect-button">添加用户</a-button>
                <a-button @click="batchDel" type="danger" v-if="selectionRows.length>0" ghost icon="minus"  class="theme--perfect-button">删除</a-button>
              </div>
            </template>
            <template v-slot:toolbar_tools>
              <vxe-button style="margin-right:12px;" @click="handleExportXls('用户列表')" icon="vxe-icon--download" circle></vxe-button>
            </template>
          </vxe-grid>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <!-- table区域-end -->
    <role-modal ref="modalFormRole" @ok="modalFormOkRole"></role-modal>
    <role-without-user-modal ref="modalForm" @ok="modalFormOk" />
    <perssion-modal ref="perssionModal" />
  </page-layout>
</template>

<script>
import RoleModal from './modules/RoleModal'
import RoleWithoutUserModal from './modules/RoleWithoutUserModal'
import PerssionModal from './modules/PerssionModal'
import PageLayout from '@/layouts/PageLayout'
import { getAction, deleteAction } from '@/services/manage'
import { roleDelUsers } from '@/services/system'
import { filterObj } from '@/utils/util'
import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/store/mutation-types'
import { VxeTableMixin } from '@/mixins/VxeTableMixin'
export default {
  name: 'RoleList',
  components: {
    RoleModal,
    PageLayout,
    RoleWithoutUserModal,
    PerssionModal
  },
  mixins: [VxeTableMixin],
  data() {
    return {
      queryParamRole: {},
      tableToolbarRole: {
        refresh: {
          query: () => {
            this.loadDataRole(1)
          }
        },
        buttons: [
          { code: 'add', name: '新增', status: 'perfect', icon: 'vxe-icon--plus' },
          { code: 'delete', name: '删除', status: 'perfect', icon: 'vxe-icon--minus' }
        ],
        perfect: true,
        export: true,
        print: true,
        zoom: true,
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      dataSourceRole: [],
      ipaginationRole: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      columnsRole: [
        { type: 'radio', width: 40 },
        { type: 'seq', width: 40 },
        {
          title: '角色名称',
          align: 'center',
          field: 'name'
        },
        {
          title: '描述',
          align: 'center',
          field: 'description'
        },
        {
          title: '操作',
          field: 'action',
          slots: { default: 'action' },
          align: 'center',
          width: 170
        }
      ],
      columns: [
        { type: 'checkbox', width: 40 },
        { type: 'seq', width: 40 },
        {
          title: '用户账号',
          align: 'center',
          field: 'username',
          sorter: true
        },
        {
          title: '用户姓名',
          align: 'center',
          field: 'nickname'
        },
        {
          title: '是否有效',
          align: 'center',
          field: 'accountNonExpired',
          slots: { default: ({ row }) => {
            return row.accountNonExpired === true ? '是' : '否'
          } }
        }
      ],
      url: {
        roleList: '/role/page',
        roleDelete: '/role/remove/',
        roleDeleteBatch: '/role/remove/deleteBatch/'
      },
      selectedRowKeysRole: [],
      selectionRowsRole: [],
      loadingRole: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      disableMixinCreated: true,
      roleId: ''// 选择行角色id
    }
  },
  computed: {
    leftColMd() {
      return this.selectedRowKeysRole.length === 0 ? 24 : 12
    },
    rightColMd() {
      return this.selectedRowKeysRole.length === 0 ? 0 : 12
    },
    optionsRole() {
      return {
        rowId: 'id',
        border: true,
        resizable: true,
        loading: this.loadingRole,
        align: 'center',
        height: this.height,
        'toolbar-config': this.tableToolbarRole,
        'export-config': {},
        'custom-config': { storage: { visible: true, resizable: true }}
      }
    }
  },
  methods: {
    onSelectChangeRole({ row }) {
      this.selectedRowKeysRole = [row.id]
      this.selectionRowsRole = [row]
      this.loadData(1)
    },
    searchQueryRole() {
      // this.selectedRowKeysRole = []
      // this.selectionRowsRole = []
      this.loadDataRole(1)
    },
    searchResetRole() {
      // this.selectedRowKeysRole = []
      // this.selectionRowsRole = []
      this.queryParamRole = {}
      this.loadDataRole(1)
    },
    loadDataRole(arg) {
      if (!this.url.roleList) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipaginationRole.current = 1
      }
      var params = this.getQueryParamsRole()// 查询条件
      this.loadingRole = true
      getAction(this.url.roleList, params).then((res) => {
        if (res.success) {
          this.dataSourceRole = res.result.content || res.result
          this.ipaginationRole.total = res.result.totalElements
          this.$nextTick(() => {
            const row = this.$refs.vxeTableRole.getRowById(this.selectedRowKeysRole[0])
            this.$refs.vxeTableRole.setRadioRow(row)
          })
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loadingRole = false
      })
    },
    getQueryParamsRole() {
      // 获取查询条件
      const sqp = {}
      const queryParam = new Criteria()
      queryParam.addCriterions(this.queryParamRole, OPERATOR.LIKE)
      var param = Object.assign(sqp, { criteria: queryParam.getEncode() })
      param.pageNo = this.ipaginationRole.currentPage
      param.pageSize = this.ipaginationRole.pageSize
      return filterObj(param)
    },
    modalFormOkRole() {
      this.loadDataRole()
    },
    handlePageChange({ currentPage, pageSize }) {
      this.ipaginationRole.currentPage = currentPage
      this.ipaginationRole.pageSize = pageSize
      this.loadDataRole()
    },
    handleAddRole() {
      this.$refs.modalFormRole.add()
      this.$refs.modalFormRole.title = '新增'
      this.$refs.modalFormRole.disableSubmit = false
    },
    handleDeleteRole: function(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      deleteAction(`${this.url.roleDelete}${id}`).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadDataRole()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleEditRole: function(record) {
      this.$refs.modalFormRole.edit(record)
      this.$refs.modalFormRole.title = '编辑'
      this.$refs.modalFormRole.disableSubmit = false
    },
    handleEditPerssion: function(record) {
      this.$refs.perssionModal.show(record.id)
    },
    loadData(arg) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()// 查询条件
      this.loading = true
      getAction(`/role/list/${this.selectedRowKeysRole[0]}/within`, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.content || res.result
          this.ipagination.total = res.result.totalElements
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    handleAdd() {
      if (!this.selectedRowKeysRole[0]) {
        this.$message.warning('请先选择角色')
        return false
      }
      this.$refs.modalForm.show(this.selectedRowKeysRole[0])
    },
    batchDel() {
      if (!this.selectedRowKeysRole[0]) {
        this.$message.warning('请先选择角色')
        return false
      }
      if (this.selectionRows.length) {
        roleDelUsers(this.selectedRowKeysRole[0], this.selectedRowKeys).then(res => {
          if (res.success) {
            this.loadData()
          }
        })
      } else {
        this.$message.warning('请选择解除关联的用户')
      }
    }
  },
  mounted() {
    this.loadDataRole(1)
  }
}
</script>
<style scoped lang="scss">
  @import '@/assets/css/vxe-table-common.scss';
</style>
